/**
 * Created by YJH on 2018/5/24.
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    ListView,
    DeviceEventEmitter,
    RefreshControl,
} from 'react-native';

import GitHubTrending from 'GitHubTrending';
import NavigationBarComponent from '../NavigationBarComponent';
import ScrollableTabView, {ScrollableTabBar} from 'react-native-scrollable-tab-view';
import DataRespository, {FLAG_STORAGE} from '../../expand/dao/DataRespository';
import LanguageDao, {FLAG_LAN} from '../../expand/dao/LanguageDao';
import RespositoryTrendingCell from '../../common/RespositoryTrendingCell';
import RespositoryCell from '../../common/RespositoryCell';
import RepositoryDetailPage from '../../page/home/RepositoryDetailPage'
import FavoriteDao from '../../expand/dao/FavoriteDao';
import ProjectModulePopular from '../../module/ProjectModulePopular';
import BasePage from '../home/BasePage';


const URL = 'https://github.com/trending/';
export default class FavoritePage extends BasePage {

    constructor(props) {
        super(props);
        this.LanguageDao = new LanguageDao(FLAG_LAN.flagLanguage);
        this.state = {
            txtFetch: '拉取数据中，请稍后..',
            url: URL,
            theme:this.props.hTheme,
        };

        this.gitHubTrending = new GitHubTrending();


    }

    render() {
        //防止渲染抖动:因为方法render执行在componentDidMount之后，执行到render时由于还是不知道TabPage的数量，无法计算显示渲染长度。
        const tabs = <ScrollableTabView
            renderTabBar={() => <ScrollableTabBar/>}
            tabBarBackgroundColor={this.state.theme.themeColor}
            tabBarInactiveTextColor='mintcream'
            tabBarActiveTextColor='white'
            tabBarUnderlineStyle={{backgroundColor: 'white', height: 3}}
        >
            <PopularTabPage tabLabel='收藏' flag={FLAG_STORAGE.flag_popular} isPopular={true} {...this.props}/>
            <PopularTabPage tabLabel='点赞' flag={FLAG_STORAGE.flag_trending} isPopular={false} {...this.props}/>
        </ScrollableTabView>;

        return (
            <View style={styles.container}>
                <NavigationBarComponent
                    style={this.state.theme.styles.navBar}
                    title={'搜藏'}
                    statusBar={{backgroundColor:this.state.theme.themeColor}}/>
                {tabs}
            </View>
        )
    }
}


class PopularTabPage extends Component {
    constructor(props) {
        super(props);
        this.isPopular = this.props.flag === FLAG_STORAGE.flag_popular;
        this.dataRespository = new DataRespository(this.props.flag);
        this.favoriteDao = new FavoriteDao(this.props.flag);
        this.state = ({
            searchKey: this.props.tabLabel,
            dataSource: new ListView.DataSource({
                rowHasChanged: (r1, r2) => r1 !== r2
            }),
            isLoading: false,
            favoriteKeys: [],
        })
    }


    /** 该方法是在上个组件传值到当前组件过程 回调此方法
     * 由 <TabPage key={i} tabLabel={lan.name} timeSpan={this.state.timeSpan}{...this.props}/>实现
     * 当上个组件中的timeSpan发生变化就会调用下面的方法并将timeSpan传给nextProps
     * */
    componentWillReceiveProps(nextProps) {
        if (nextProps.timeSpan !== this.props.timeSpan) {
            this.onLoad(nextProps.timeSpan, true);
        }
    }


    updateState(dic) {
        if (!this) return;
        this.setState(dic);
    }


    /** 加载网络数据*/
    onLoad(isRefresh) {
        this.setState({
            isLoading: isRefresh,
        });

        this.favoriteDao.getAllItems()
            .then(items => {
                var resultData = [];
                for (let i = 0, l = items.length; i < l; i++) {
                    resultData.push(new ProjectModulePopular(items[i], true));
                }
                this.updateState({dataSource: this.getDataSource(resultData), isLoading: false})
            })
            .catch(error => {
                this.updateState({isLoading: false})
            });

    }

    getDataSource(projectModules) {
        // DeviceEventEmitter.emit('showToast', '-->>' + projectModules.length);
        return this.state.dataSource.cloneWithRows(projectModules);
    }

    componentDidMount() {
        //页面装载之后调用
        this.onLoad(true);

    }

    renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return <View style={styles.item_line}>
        </View>
    }

    goItemDetail(data) {
        this.props.navigator.push({
            component: RepositoryDetailPage,
            params: {
                projectModule: data,
                isTrending: this.isPopular?false:true,
                ...this.props,//这个是延展属性，而延展属性中会有navigator
            },
        });
    }

    /** 这个是从二级组件回调的方法*/
    onFavoritePressed(item, isFavorite) {
        if (isFavorite)
            this.favoriteDao.savaFavoriteItem(this.isPopular ? item.id.toString() : item.fullName, JSON.stringify(item));
        else this.favoriteDao.removeFavoriteItem(this.isPopular ? item.id.toString() : item.fullName);

        DeviceEventEmitter.emit('popular_itemStateChanged');
    }


    renderRow(projectModule) {
        let CellComponent = this.isPopular ? RespositoryCell : RespositoryTrendingCell;
        let key = this.isPopular ? projectModule.item.id : projectModule.item.fullName;
        return <CellComponent
            key={key}
            goItemDetail={() => {
                this.goItemDetail(projectModule);
            }}
            projectModule={projectModule}
            onFavoritePressed={(item, isFavorite) => this.onFavoritePressed(item, isFavorite)}

            {...this.props}
        />
    }

    onLoadRefresh() {
        setTimeout(() => {
            this.onLoad(true);
        }, 1500);
    }


    render() {
        return <View style={{flex: 1}}>
            <ListView
                dataSource={this.state.dataSource}
                renderRow={(data) => this.renderRow(data)}
                renderSeparator={(sectionID, rowID, adjacentRowHighlighted) => this.renderSeparator(sectionID, rowID, adjacentRowHighlighted)}
                enableEmptySections={true}
                // renderFooter={() => this.renderFooter()}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => this.onLoadRefresh()}
                    />}
            />

        </View>
    }

}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#FCFCFC',
    },
    newTextStyle: {
        fontSize: 24,
    },
    ViewForTextStyle: {
        height: 60,
        width: 180,
        borderColor: 'green',
        borderWidth: 1,
        borderRadius: 5,
        alignSelf: 'center',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ddd',
        margin: 5
    },

    boy_text: {
        fontSize: 18,
        color: 'black',
        alignSelf: 'center',
    },
    tab_image: {
        width: 20,
        height: 20,
    },
    text: {
        fontSize: 18,
        marginTop: 10,
        alignSelf: 'center',
    },
    button: {
        height: 60,
        marginTop: 30,
        fontSize: 20,
        alignSelf: 'center',
    },
    edt: {
        height: 50,
        marginTop: 30,
        minWidth: 300,
        alignSelf: 'center',
        borderColor: '#02F78E',
    },
    item_row: {
        height: 60
    }, item_line: {
        height: 1,
        backgroundColor: '#FCFCFC'
    },
});